package org.luxor.commons.security.component;

import org.luxor.commons.core.utils.HttpContextUtils;
import org.luxor.commons.core.utils.StrKit;
import org.luxor.commons.core.web.RestStatus;
import org.luxor.commons.core.web.data.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.util.MimeTypeUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 403 匿名用户(未登陆),未授权访问受限资源响应处理器
 *
 * @author yanxinming @date 2020/06/03
 */
public class RestAuthExceptionEntryPoint implements AuthenticationEntryPoint {
    private static final Logger log = LoggerFactory.getLogger(RestAuthExceptionEntryPoint.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding(StrKit.CHARSET_NAME);
        response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);

        log.debug("当前来源IP:[{}] 未授权访问:[{}]", HttpContextUtils.getRemoteAddr(request), request.getRequestURI());

        R result = new R<>(RestStatus.UNAUTHORIZED, e.getMessage());
        HttpContextUtils.sendJson(response, result);
    }
}
